OOCSS


Posted by TempuraEngineer on 2022-05-01

OOCSS是甚麼

OOCSS(Object Oriented CSS)是一種CSS的設計模式。它可以提升css的彈性複用性,通常用於大型專案
BootstrapTailwind有就是很好的例子。尤其Tailwind的OOCSS純度又比Bootstrap高。

使用OOCSS的網站
class看起來又臭又長是一個缺點,不過如果用Vue、React等框架做成組件的話,就可以把髒髒的藏起來了

大致可以分為2個概念,核心概念都是將common style抽象化,減少重複

  1. 將structure從skin拆出來
    把組件間的common style抽象出來,減少重複

    skin:visual features,如background-color, color
    structure:invisible features,如width, padding, margin

     /* 截取bootstrap.css */
    
     .btn {
       display: inline-block;
       font-weight: 400;
       color: #212529;
       text-align: center;
       vertical-align: middle;
       -webkit-user-select: none;
       -moz-user-select: none;
       -ms-user-select: none;
       user-select: none;
       background-color: transparent;
       border: 1px solid transparent;
       padding: 0.375rem 0.75rem;
       font-size: 1rem;
       line-height: 1.5;
       border-radius: 0.25rem;
       transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
     }
    
     .btn-primary {
       color: #fff;
       background-color: #007bff;
       border-color: #007bff;
     }
    
     .btn-success {
       color: #fff;
       background-color: #28a745;
       border-color: #28a745;
     }
    
  2. 將container從content拆出來
    元件(content)不依賴外層(container),可降低耦合度,進而減少重複的style

    Styles used for Content elements should be independent of the container class so that it can be used without restrictions on their parent element. For example, this is a regular styling for a sidebar.


OOCSS重點摘要

  1. 彈性,易於重複使用
    不綁定HTML tag、id,因為會減少彈性
    模組化、細分style來減少耦合,進而提升彈性,最後達到重複使用的效果

  2. 語意化,有助於SEO

  3. 提升效能
    因為將common style抽象出去,減少重複的style避免使用後代選取器都能增進效能

    If you have fewer styles that are repeated in your CSS, then this will lead to smaller file sizes and thus faster downloading of those resources.

    It’s true that markup will be more cluttered and thus create larger HTML files. But in many cases the amount of loss in markup performance will be greatly surpassed by the amount of gain in stylesheet performance.

  4. (專案的)可擴展性
    當專案越來越大的時候如果沒有用OOCSS,那style就會一直增加。
    反之如果用OOCSS,只要把原有的class套上去就好,因此也會更易於維護


📖

An Introduction To Object Oriented CSS
What is OOCSS
OOCSS Methodology


#OOCSS







Related Posts

[26] 強制轉型 - 隱含地 Boolean、運算子 || 、 &&

[26] 強制轉型 - 隱含地 Boolean、運算子 || 、 &&

用 JavaScript 學習資料結構和演算法:堆疊(Stack)篇

用 JavaScript 學習資料結構和演算法:堆疊(Stack)篇

Web開發學習筆記06 — Function Scope vs. Block Scope、IIFE

Web開發學習筆記06 — Function Scope vs. Block Scope、IIFE


Comments